<?php

define('ME', array_shift($argv));
define('SCRIPT_FS_DIR', getcwd());

function store_file_contents($file, &$content) {

	if (is_file($file) && is_readable($file)) {

		echo "file exists: " . $file . "\r\n";

		$content[] = file_get_contents($file);

		return true;

	} else {

		echo "file do not exist: " . $file . "\r\n";

	}

	return false;

}

function compact_file_contents($list_file) {

	echo 'file size? ' . filesize($list_file) . ' -- ' . $list_file . "\r\n";

	if ($fp = fopen($list_file, 'r')) {

		$contents = fread ($fp , filesize($list_file));

		fclose($fp);

		$lines = preg_split('/(\r\n|\n)+/', $contents);

		$js_contents = array();

		foreach ($lines as $line) {

			$line = preg_replace(
				array(
					"/^\;.*$/",
					"/^\s*(.*)\s*$/"
				),

				array(
					'',
					'$1'
				),

				$line
			);

			if (!$line) {

				continue;

			}

			$fs_path = SCRIPT_FS_DIR . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $line);

			// add more!
			if (store_file_contents($fs_path, $js_contents)) {

				$more = preg_replace('/\.js$/i', '', $fs_path) . DIRECTORY_SEPARATOR . 'more.js';

				store_file_contents($more, $js_contents);

			}

		}

		if (count($js_contents)) {

			return implode("\r\n", $js_contents);

		}

	}

}



$list_file = array_shift($argv);

$target_file = array_shift($argv);

if (is_file($list_file) &&
	is_readable($list_file) &&
	is_dir($target_dir = dirname($target_file))
) {

	echo "compacting using file list ${list_file} \r\n";
	$contents = compact_file_contents($list_file);

	file_put_contents($target_file, $contents);

}
